package net.mayee.alice.functions.base;

import com.alibaba.druid.util.StringUtils;
import jetbrick.template.JetAnnotations;
import jetbrick.template.runtime.InterpretContext;
import jetbrick.template.web.JetWebContext;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;

@JetAnnotations.Functions
public class BaseFunctions {

    private static String path;
    private static String basePath;
    private static final String DEFAULT_MESSAGE = "";

    static {
        path = loadPath();
        basePath = loadBasePath();
    }

    private static String loadPath() {
        InterpretContext ctx = InterpretContext.current();
        HttpServletRequest request = (HttpServletRequest) ctx.getValueStack().getValue(JetWebContext.REQUEST);
        return request.getContextPath();
    }

    private static String loadBasePath() {
        InterpretContext ctx = InterpretContext.current();
        HttpServletRequest request = (HttpServletRequest) ctx.getValueStack().getValue(JetWebContext.REQUEST);
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + getPath() + "/";
    }

    public static String getMessage(String key) {
        InterpretContext ctx = InterpretContext.current();
        HttpServletRequest request = (HttpServletRequest) ctx.getValueStack().getValue(JetWebContext.REQUEST);
        return new RequestContext(request).getMessage(key, DEFAULT_MESSAGE);
    }

    public static String getMessage(String key, String dufalutMessage) {
        InterpretContext ctx = InterpretContext.current();
        HttpServletRequest request = (HttpServletRequest) ctx.getValueStack().getValue(JetWebContext.REQUEST);
        return new RequestContext(request).getMessage(key, dufalutMessage);
    }

    public static String getMessage(String key, String[] values) {
        InterpretContext ctx = InterpretContext.current();
        HttpServletRequest request = (HttpServletRequest) ctx.getValueStack().getValue(JetWebContext.REQUEST);
        return new RequestContext(request).getMessage(key, values, DEFAULT_MESSAGE);
    }

    public static String getPath() {
        if (StringUtils.isEmpty(path)) {
            path = loadPath();
        }
        return path;
    }

    public static String getBasePath() {
        if (StringUtils.isEmpty(basePath)) {
            basePath = loadBasePath();
        }
        return basePath;
    }


}

